import { useEffect, useRef, useState } from 'react';
import Vditor from 'vditor';
import 'vditor/dist/index.css';

import './index.less';

interface IProps {
  value?: string;
  onChange?: (v: string) => void;
}

const MarkdownEditor = (props: IProps) => {
  const { value = '', onChange } = props;
  const vditorRef = useRef<any>(null);
  const vditorDOMRef = useRef<HTMLDivElement | null>(null);
  const [vditorReady, setVditorReady] = useState(false); // 编辑器初始化完成滞后于数据就绪，导致感知不到第一次数据灌入，因此用标志位实现数据灌入检测

  useEffect(() => {
    init();
    return () => {
      if (vditorDOMRef.current) {
        vditorDOMRef.current.innerHTML = '';
      }
    };
  }, []);

  useEffect(() => {
    if (!vditorReady) {
      return;
    }
    if (vditorRef.current) {
      vditorRef.current.setValue(value);
    }
  }, [vditorReady]);

  useEffect(() => {
    if (vditorRef.current) {
      vditorRef.current.setValue(value);
    }
  }, [value]);

  const init = () => {
    const container = vditorDOMRef.current;
    console.log('c', container);
    if (!container) {
      return;
    }
    container.innerHTML = '';
    const vditor = new Vditor(container, {
      height: '200px',
      mode: 'ir',
      preview: {
        markdown: {
          codeBlockPreview: false
        }
      },
      // input: (v) => {
      //   onChange?.(v);
      // },
      blur: (v) => {
        onChange?.(v);
      },
      after: () => {
        vditorRef.current = vditor;
        setVditorReady(true);
      },
      toolbar: [],
      cache: {
        enable: false, // 禁用localstorage缓存
      },
    });
  };

  return (
    <div className="editor__container">
      <div ref={vditorDOMRef}></div>
    </div>
  );
};

export default MarkdownEditor;
